﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Text;

public partial class Register : System.Web.UI.Page
{
    SqlConnection conn;
    protected void Page_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ShopLaptopConnectionString"].ConnectionString);
    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        ArrayList listCusUser = GetAllCusUser();
        foreach (string item in listCusUser)
        {
            if (item.Equals(txtUsername.Text))
            {
                ShowPopUpMsg("Username da ton tai");
                return;
            }
        }
        SqlCommand cmd = new SqlCommand(@"Insert into Customer
                        values(@CusUser,@CusPass,@CusName,@CusPhone,@CusAdd,@CusEmail,1)", conn);
        cmd.Parameters.AddWithValue("@CusUser", txtUsername.Text);
        cmd.Parameters.AddWithValue("@CusPass", txtPassword.Text);
        cmd.Parameters.AddWithValue("@CusName", txtName.Text);
        cmd.Parameters.AddWithValue("@CusPhone", txtPhone.Text);
        cmd.Parameters.AddWithValue("@CusAdd", txtAddress.Text);
        cmd.Parameters.AddWithValue("@CusEmail", txtEmail.Text);
        int check = 0;
        conn.Open();
        check = cmd.ExecuteNonQuery();
        if (check > 0)
        {
            ShowPopUpMsg("Register sucessful");
        }
        conn.Close();
        
        
    }

    private void ShowPopUpMsg(string msg)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("alert('");
        sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
        sb.Append("');");
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
    }

    private ArrayList GetAllCusUser()
    {
        ArrayList listCusUser = null;
        SqlCommand cmd = new SqlCommand("Select CusUser from Customer",conn);
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        listCusUser = new ArrayList();
        while (reader.Read())
        {
            string a = reader["CusUser"].ToString();
            //Response.Write(reader["CusUser"].ToString());
            listCusUser.Add(a);
        }
        conn.Close();
        return listCusUser;
    }
    protected void ltbnShopCart_Click(object sender, EventArgs e)
    {
        if (Session["proID"] != null)
        {
            Response.Redirect("Cart.aspx");
        }
        Response.Redirect("CartEmpty.aspx");
    }
}
